package com.spring.security.social.qq.connet;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * QQ自定义Template  解析
 */
public class QQOAuth2Template extends OAuth2Template {

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        // 设置成true才会将clientId和clientSecret放到请求参数中
        setUseParametersForClientAuthentication(true);
    }

    /**
     * 自定义发送请求并解析
     *
     * @param accessTokenUrl
     * @param parameters
     * @return
     */
    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String result = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
        System.out.println("响应数据：" + result);
        return createAccessGrant(result);
    }


    /**
     * 根据返回的结构创建AccessGrant 成功返回，即可在返回包中获取到Access Token。 如：
     * access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
     *
     * @param responseResult
     * @return
     */
    private AccessGrant createAccessGrant(String responseResult) {
        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseResult, "&");
        String access_token = StringUtils.substringAfterLast(items[0], "=");
        String expires_in = StringUtils.substringAfterLast(items[1], "=");
        String refresh_token = StringUtils.substringAfterLast(items[2], "=");
        return new AccessGrant(
                access_token, StringUtils.EMPTY, refresh_token, Long.valueOf(expires_in));
    }


    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = super.createRestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}
